package com.mangoerp.demo;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.mangoerp.common.Result;
import com.mangoerp.error.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yincb
 * @title: OrderController
 * @date 2021/12/79:49
 */
@RestController
public class OrderController {

    private Map<Integer, Order> orders =  new HashMap<>();

    // 配置热点参数规则 资源名称必须是@SentinelResource
    @SentinelResource(value = "getOrder",
            blockHandlerClass = ExceptionHandler.class,
            blockHandler="handleException",
            fallbackClass= ExceptionHandler.class,
            fallback="fallback")
    @GetMapping("/getOrder/{orderId}")
    public Result getOrder(@PathVariable("orderId") Integer orderId){
        return Result.ok().put("data", orders.get(orderId));
    }

    @GetMapping("/getAllOrder")
    public Result getAllOrder(){
        List<Order> result = new ArrayList<>();
        orders.values().stream().forEach(order -> result.add(order));
        return Result.ok().put("data", orders);
    }


    @PostConstruct
    public void init(){
        orders.put(1,Order.builder().orderId(1).price(BigDecimal.valueOf(20)).num(1).sku("SKU001").build());
        orders.put(2,Order.builder().orderId(2).price(BigDecimal.valueOf(30)).num(1).sku("SKU001").build());
        orders.put(3,Order.builder().orderId(3).price(BigDecimal.valueOf(100)).num(2).sku("SKU001").build());
    }

}
